import axios from 'axios'
import store from '@/store'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(config => {
  const token = store.state.user.token
  // 如果当前存有token,就加在请求头上
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
}
,
error => {
  return Promise.reject(error)
})
export default service

// 添加响应拦截器
service.interceptors.response.use(function(response) {
  // 对响应数据做点什么
  if (response.data.success) {
    return response.data
  } else {
    return Promise.reject(new Error('请求出现错误'))
    // 如果response.data.success为false就抛出一个错误
  }
}, function(error) {
  // 对响应错误做点什么
  console.log(error)
  console.dir(error.response.data.code === 10002)
  if (error.response.data.code === 10002) {
    store.commit('user/removeTokenAndUserInfo')
    console.log(router)
    router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
  }
  return Promise.reject(error)
})
